<template>
  <label class="switch-container">
    <input type="checkbox" class="switch-input" :checked="checkedVal" @change="toggleSwitch" />
    <span class="switch-slider" :style="{ backgroundColor: checkedVal ? color : '' }"></span>
    <span v-if="label" class="switch-label">{{ label }}</span>
  </label>
</template>

<script>
export default {
  name: 'a-switch',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    label: {
      type: String,
      default: ''
    },
    color: {
      type: String,
      default: ''
    },
    checked: {
      type: Boolean,
      default: null
    }
  },
  data() {
    return {
      checkedVal: this.modelValue,
    }
  },
  emits: ['update:modelValue', "change"],
  watch: {
    modelValue(newValue) {
      this.checkedVal = newValue;
    }
  },
  mounted() {
    if (this.checked !== null) {
      this.checkedVal = this.checked;
    }
  },
  methods: {
    toggleSwitch(e) {
      this.checkedVal = e.target.checked;
      this.$emit('update:modelValue', this.checkedVal);
      this.$emit('change', this.checkedVal);
    }
  }
}
</script>

<style scoped>
.switch-container {
  display: inline-flex;
  align-items: center;
  cursor: pointer;
}

.switch-input {
  position: absolute;
  opacity: 0;
  width: 0;
  height: 0;
}

.switch-slider {
  position: relative;
  display: inline-block;
  width: 36px;
  height: 20px;
  background-color: var(--light-background-color);
  border-radius: 20px;
  transition: all 0.4s cubic-bezier(0.68, -0.6, 0.32, 1.6);
}

.switch-slider:before {
  position: absolute;
  content: "";
  height: 16px;
  width: 16px;
  left: 2px;
  bottom: 2px;
  background-color: var(--font-color-light);
  border-radius: 50%;
  transition: all 0.4s cubic-bezier(0.68, -0.6, 0.32, 1.6);
  transform: scale(1);
}

.switch-input:checked+.switch-slider:before {
  transform: translateX(16px) scale(1.1);
}

.switch-input:checked+.switch-slider {
  background-color: var(--primary-color);
}

.switch-input:checked+.switch-slider:before {
  transform: translateX(16px);
}

.switch-label {
  margin-left: 8px;
}
</style>